package com.gavinwind.uic.customer.aop.log;

import com.gavinwind.uic.customer.config.ApplicationConstants;
import com.sinosoft.platform.common.logger.SinoCloudLogger;
import com.sinosoft.platform.common.logger.SinoCloudLoggerFactory;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.env.Environment;

import javax.inject.Inject;
import java.util.Arrays;

/**
 * Aspect for logging execution of service and repository Spring components.
 */
@Aspect
public class LoggingAspect {

    private final SinoCloudLogger log = SinoCloudLoggerFactory.getLogger(this.getClass());
    // ①通过匿名内部类覆盖ThreadLocal的initialValue()方法，指定初始值
    private static ThreadLocal<Long> timeInt = new ThreadLocal<Long>() {
        public Long initialValue() {
            return 0l;
        }
    };
    @Inject
    private Environment env;

//    @Pointcut("within(com..biz.service..*) || within(com..web.restapi..*)")
    @Pointcut("public within(com..web.restapi..*)")
    public void loggingPointcut() {
    }

    @AfterThrowing(pointcut = "loggingPointcut()", throwing = "e")
    public void logAfterThrowing(JoinPoint joinPoint, Throwable e) {
        if (env.acceptsProfiles(ApplicationConstants.SPRING_PROFILE_DEVELOPMENT)) {
            log.error("Exception in {}.{}() with cause = \'{}\' and exception = \'{}\'", joinPoint.getSignature().getDeclaringTypeName(),
                joinPoint.getSignature().getName(), e.getCause() != null? e.getCause() : "NULL", e.getMessage(), e);

        } else {
            log.error("Exception in {}.{}() with cause = {}", joinPoint.getSignature().getDeclaringTypeName(),
                joinPoint.getSignature().getName(), e.getCause() != null? e.getCause() : "NULL");
        }
    }

    @Around("loggingPointcut()")
    public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
        if (log.isDebugEnabled()) {
            log.debug("Enter: {}.{}() with argument[s] = {}", joinPoint.getSignature().getDeclaringTypeName(),
                joinPoint.getSignature().getName(), Arrays.toString(joinPoint.getArgs()));
        }
        try {
            Object result = joinPoint.proceed();
            if (log.isDebugEnabled()) {
                log.debug("Exit: {}.{}() with result = {}", joinPoint.getSignature().getDeclaringTypeName(),
                    joinPoint.getSignature().getName(), result);
            }
            return result;
        } catch (IllegalArgumentException e) {
            log.error("Illegal argument: {} in {}.{}()", Arrays.toString(joinPoint.getArgs()),
                    joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());

            throw e;
        }
    }
    @Before(value="loggingPointcut()")
    public void beforeMethod(ProceedingJoinPoint joinPoint) throws Throwable {
        timeInt.set(System.currentTimeMillis());
    }
    @After(value="loggingPointcut()")
    public void afterMethod(ProceedingJoinPoint joinPoint) throws Throwable {
        Long beforeTime = timeInt.get();
        Long afterTime = System.currentTimeMillis();
        Long dureTime = afterTime - beforeTime;
        String className = joinPoint.getSignature().getDeclaringTypeName();
        String methodName = joinPoint.getSignature().getName();
        log.info("Exit: {}.{}() costs {}." ,className,methodName,dureTime+"");
    }

}
